package com.zhang.gmall.realtime.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.java.tuple.Tuple2;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * @title: 查询维度工具类
 * @author: zhang
 * @date: 2022/3/7 23:29
 */

public class DimUtil {
    //引入旁路缓存（redis）
    public static JSONObject getDimInfo(String tableName, String id) {
        return getDimInfo(tableName,Tuple2.of("id",id));
    }

    /**
     * 查询维度数据，加入旁路缓存优化。
     * 思路：先从缓存中查询维度数据，如果缓存中存在维度数据，直接将维度数据返回（缓存命中）；
     * 如果缓存中不存在当前查询的维度数据，那么发送请求到Phoenix表种查询并将结果放到缓存中。
     *
     * @param tableName
     * @param columnAndValues
     * @return
     */
    public static JSONObject getDimInfo(String tableName, Tuple2<String, String>... columnAndValues) {
        //拼接redis的key
        StringBuilder redisKey = new StringBuilder("DIM:" + tableName + ":");
        //拼接SQL
        StringBuilder selectSql = new StringBuilder("select * from " + tableName + " where ");
        for (int i = 0; i < columnAndValues.length; i++) {
            String clumnName = columnAndValues[i].f0;
            String clumnValue = columnAndValues[i].f1;
            selectSql.append(clumnName + " ='" + clumnValue + "' ");
            redisKey.append(clumnValue);
            if (i < columnAndValues.length - 1) {
                selectSql.append(" and ");
                redisKey.append("_");
            }
        }

        //先去查缓存
        Jedis jedis = null;
        String jsonStr = null;
        JSONObject dimJsonObj = null;
        try {
            System.out.println("-------开启redis客户端-------");
            jedis = JedisUtil.getJedis();
            jsonStr = jedis.get(redisKey.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("从Redis中获取维度数据失败");
        }
        //命中缓存
        if (jsonStr != null && jsonStr.length() > 0){
            dimJsonObj = JSON.parseObject(jsonStr);
            //重制过期时间
            jedis.expire(redisKey.toString(),60*60*24);
        }else {
            //没有命中缓存，发送Phoenix请求查询维度数据
            System.out.println("从Phoenix查询的SQL:" + selectSql);
            List<JSONObject> jsonObjects = PhoenixUtil.queryList(selectSql.toString(), JSONObject.class, false);
            if (jsonObjects != null && jsonObjects.size() > 0) {
                dimJsonObj = jsonObjects.get(0);
                //把查询结果写入redis缓存
                if (jedis!=null){
                    jedis.setex(redisKey.toString(), 60*60*24,dimJsonObj.toJSONString());
                }

            } else {
                //从Phoenix表中没有查询到维度数据
                System.out.println("在维度表中没有该维度数据" + selectSql);
            }
        }

        if (jedis!=null){
            System.out.println("-------关闭redis客户端-------");
            jedis.close();
        }

        return dimJsonObj;
    }

    //维度发生变化删除redis缓存数据
    public static void deleteCached(String tableName,String id){
        String redisKey = "DIM:"+tableName+":"+id;
        Jedis jedis = null;
        try {
            jedis = JedisUtil.getJedis();
            jedis.del(redisKey);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("删除redis缓存失败~~~~~~");
        }finally {
            if (jedis!=null){
                jedis.close();
            }
        }
    }


    //根据维度主键，获取维度对象 (没有引入缓存)
    //select * from GMALL_REALTIME_2022.DIM_BASE_TRADEMARK where id ='14';
    public static JSONObject getDimInfoNoCache(String tableName, Tuple2<String, String>... columnAndValues) {
        //拼接SQL
        StringBuilder selectSql = new StringBuilder("select * from " + tableName + " where ");
        for (int i = 0; i < columnAndValues.length; i++) {
            Tuple2<String, String> columnAndValue = columnAndValues[i];
            String columnName = columnAndValue.f0;
            String columnValue = columnAndValue.f1;
            selectSql.append(columnName + "='" + columnValue + "'");
            if (i < columnAndValues.length - 1) {
                selectSql.append(" and ");
            }
        }

        System.out.println("从Phoenix查询的SQL:" + selectSql);
        //从Phoenix表中查询数据，底层调用的还是PhoenixUtil
        List<JSONObject> jsonObjects = PhoenixUtil.queryList(selectSql.toString(), JSONObject.class, false);
        JSONObject dimJsonObj = null;
        if (jsonObjects != null && jsonObjects.size() > 0) {
            dimJsonObj = jsonObjects.get(0);
        } else {
            //从Phoenix表中没有查询到维度数据
            System.out.println("在维度表中没有该维度数据" + selectSql);
        }
        return dimJsonObj;
    }

    public static void main(String[] args) {
        //System.out.println(getDimInfoNoCache("DIM_BASE_TRADEMARK", Tuple2.of("id", "12")));
       System.out.println(getDimInfo("DIM_BASE_TRADEMARK", "13"));
        //deleteCached("DIM_BASE_TRADEMARK","12");
    }
}
